﻿using Microsoft.AspNetCore.Components;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Project13776616780_01.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;

namespace Project13776616780_01.Components
{
    public partial class CategorySelector
    {
        private List<Category> categories;
        private int categoryId;

        [Parameter]
        public int CategoryId
        {
            get
            {
                return categoryId;
            }
            set
            {
                categoryId = value;
                categoryName = categories?.FirstOrDefault(x => x.Id == categoryId)?.Name;
                SetFieldValue(new KeyValuePair<int, string>(value, categoryName), true);
                if (CategoryIdChanged.HasDelegate)
                {
                    _ = CategoryIdChanged.InvokeAsync(value);
                }
            }
        }

        [Parameter]
        public EventCallback<int> CategoryIdChanged { get; set; }

        private string categoryName;
        [Inject]
        private IServiceProvider serviceProvider { get; set; }
        protected override async Task OnInitializedAsync()
        {
            await base.OnInitializedAsync();
            categories = await serviceProvider.CreateScope().ServiceProvider.GetRequiredService<DocsDbContext>().Set<Category>().ToListAsync();
            categoryName = categories.FirstOrDefault(x => x.Id == categoryId)?.Name;
            await InvokeAsync(StateHasChanged);
        }
        protected override void OnParametersSet()
        {
            base.OnParametersSet();
            if (FormItem == null)
            {
                return;
            }
            if (FormItem.OriginValueHasRendered)
            {
                return;
            }
            FormItem.OriginValueHasRendered = true;
            if (FormItem.Form.Values.Any())
            {
                categoryId = FormItem.OriginValue.Key;
                categoryName = serviceProvider.CreateScope().ServiceProvider.GetRequiredService<DocsDbContext>().Set<Category>().First(x => x.Id == categoryId)?.Name;
                SetFieldValue(new KeyValuePair<int, string>(categoryId, categoryName), true);
            }

        }

        protected override bool ShouldRender()
        {
            return true;
        }
    }
}
